package org.caowei.samples.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.caowei.samples.sevice.IStudentService;
import org.caowei.samples.vo.ExamScoreVO;
import org.caowei.samples.vo.SubjectVO;
import org.caowei.samples.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@RequestMapping(value = "/student")
public class StudentController {

	@Autowired
	private IStudentService studentService;
	
	@RequestMapping(value = "/subject")
	public String toSubjects(HttpSession session,Model model){
		UserVO uservo = (UserVO) session.getAttribute("User");
		List<SubjectVO> examSubjectList = studentService.getSubjectList(uservo);
		model.addAttribute("examSubjectList", examSubjectList);
		return "student/studentList";
	}
	
	//学生查看考试科目
	@ResponseBody
	@RequestMapping(value = "/showScore",method = RequestMethod.POST)
	public ExamScoreVO showScore(HttpSession session,Integer scoreId){
		ExamScoreVO vo = studentService.getScoreById(scoreId);
		return vo;
	}
	
	@RequestMapping(value = "/assignment",method = RequestMethod.POST)
	public String assignment(RedirectAttributes redirectAttr,HttpServletRequest request,String userId,Integer subId,Model model){
		Map<String,String[]> parameterMap = request.getParameterMap();
		Set<Entry<String,String[]>> entrySet = parameterMap.entrySet();
		List<Integer> answerIds = new ArrayList<Integer>();
		Map<String,String[]> testMap = new HashMap<String,String[]>();
		if(entrySet !=null){
			Iterator<Entry<String,String[]>> it = entrySet.iterator();
			final String TEST_PREFIX = "test";
			while(it.hasNext()){
				Entry<String,String[]> entry = it.next();
				String key = entry.getKey();
				String[] splitArrayString = key.split("_");
				if(splitArrayString.length == 2){
					if(TEST_PREFIX.equals(splitArrayString[0])){
						answerIds.add(Integer.valueOf(splitArrayString[1]));
						testMap.put(splitArrayString[1], entry.getValue());
					}
				}
			}
			ExamScoreVO score = studentService.calculateScore(answerIds,testMap,userId,subId);
			SubjectVO subjectVO = studentService.getSubjectById(subId);
			redirectAttr.addFlashAttribute("score",score);
			redirectAttr.addFlashAttribute("subject",subjectVO);
			return "redirect:/student/subjects";
		}
		return null;
	}
	
}
